<template>
  <div>
    <el-card style="max-width: 80%; margin: 0 auto">
      <el-form
        ref="updateRuleFormRef"
        style="max-width: 70%; margin: 0 auto"
        :model="updateRuleForm"
        label-width="150px"
        class="demo-ruleForm"
        status-icon
        @submit.prevent="submitCreateForm(updateRuleFormRef)"
      >
        <el-form-item label="上级栏目" prop="parentId" name="parentId">
          <el-select
            v-model="updateRuleForm.parentId"
            placeholder="请选择上级栏目"
          >
            <el-option
              v-for="item in parentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div v-for="item in tableData" :key="item.field">
          <el-form-item
            :label="item.label"
            v-if="item.display"
            :prop="
              Object.keys(updateRuleForm).find(
                (key) => updateRuleForm[key] === updateRuleForm[item.field]
              )
            "
            :name="updateRuleForm[item.field]"
            :rules="getValidationRules(item.field)"
          >
            <MyInput
              v-if="item.dataType === 1"
              v-model="updateRuleForm[item.field]"
              :inputType="'text'"
              @handleInput="handleInput"
              @blur="handleBlur(item.field)"
              @focus="handleFocus(item.field)"
            />
            <MyInput
              v-if="item.dataType === 4"
              v-model="updateRuleForm[item.field]"
              :inputType="'textarea'"
              :resize="'vertical'"
            />
            <MyInput
              v-if="item.dataType === 9"
              v-model="updateRuleForm[item.field]"
              :inputType="'textarea'"
              :resize="'vertical'"
            />
            <MyInput
              v-if="item.dataType === 2"
              v-model="updateRuleForm[item.field]"
              :inputType="'number'"
            />
            <MySelect
              v-if="item.dataType === 6"
              v-model="updateRuleForm[item.field]"
              :options="item.options"
              @change="onSelectChange"
            />
            <RadioGroupComponent
              v-if="item.dataType === 8"
              v-model="updateRuleForm[item.field]"
              :options="[
                { value: '1', label: '是' },
                { value: '0', label: '否' }
              ]"
            />
            <CheckboxGroupComponent
              v-if="item.dataType === 7"
              v-model="updateRuleForm[item.field]"
              :options="item.options"
              @change="onCheckboxChange"
            />
            <DatePicker
              v-if="item.dataType === 5"
              v-model="updateRuleForm[item.field]"
            />
            <Cascader
              v-if="item.dataType === 10"
              v-model="updateRuleForm[item.field]"
              :options="item.options"
            />
          </el-form-item>
        </div>
      </el-form>
      <div style="text-align: center">
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitCreateForm(updateRuleFormRef)"
          >
            提 交
          </el-button>
          <el-button type="primary" @click="onClose"> 关闭 </el-button>
          <el-button @click="resetUpdateForm(updateRuleFormRef)"
            >重 置</el-button
          >
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useStore } from 'vuex'
import MyInput from '@/views/components/elInput.vue'
import MySelect from '@/views/components/elSelect.vue'
import RadioGroupComponent from '@/views/components/elRadio.vue'
import CheckboxGroupComponent from '@/views/components/elCheckboxGroup.vue'
import DatePicker from '@/views/components/elDatePicker.vue'
import Cascader from '@/views/components/elCascader.vue'
import { useRoute, useRouter } from 'vue-router'
import {
  childColumn,
  createChildColumn,
  getColumnTree
} from '@/api/column/columnList.js'
import { ElMessage } from 'element-plus'
const store = useStore()
const userId = store.state.app.user.id
const updateRuleFormRef = ref()
const route = useRoute()
const router = useRouter()
const parentOptions = ref([])

const updateRuleForm = ref({
  // upperColumn: '',
  // model: '',
  channelId: '',
  parentId: '',
  root: '',
  name: '',
  path: '',
  priority: '',
  display: '',
  title: '',
  keywords: '',
  description: '',
  tplChannel: '',
  tplContent: '',
  channelStatic: '',
  contentStatic: '',
  finalStep: '',
  afterCheck: '',
  link: '',
  modelId: '',
  viewGroupIds: [],
  contriGroupIds: [],
  picPaths: [],
  picDescs: [],
  userIds: [],
  attachmentPaths: [],
  attachmentNames: [],
  attachmentFilenames: [],
  attachmentDescribes: [],
  fileGroupIds: [],
  picOrders: [],
  oldattachmentPaths: []
})

const tableData = ref([])
const getList = () => {
  const params = { root: 'source', userId: '1' }
  getColumnTree({ root: params.root, userId: params.userId }).then((res) => {
    const dataList = []
    Object.keys(res.data.map).map((item) => {
      dataList.push({
        value: item,
        label: `${res.data.map[item][0]}`
      })
    })
    parentOptions.value = dataList
  })
  const { id } = route.query
  childColumn({ id }).then((res) => {
    console.log(res)
    tableData.value = res.data.beans
    tableData.value.map((item) => {
      console.log(item)
      if (item.options) {
        const data = []
        item.options.map((list) => {
          data.push({ label: list, value: list })
        })
        item.options = data
      }
    })
  })
}

const updateRules = reactive({
  name: [{ required: true, message: '请输入栏目名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入访问路径', trigger: 'blur' }],
  priority: [{ required: true, message: '请选择排列顺序', trigger: 'blur' }],
  display: [{ required: true, message: '请选择显示', trigger: 'change' }]
})

// 获取校验规则的方法
const getValidationRules = (name) => {
  return updateRules[name] || []
}

// 关闭按钮
const onClose = () => {
  router.push({ path: 'ColumnManagement' })
}
// 弹窗提交
const submitCreateForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // updateRuleForm.value.modelId = route.query.id
      const params = {
        userId: userId,
        channelId: '',
        parentId: updateRuleForm.value.parentId,
        root: '',
        name: updateRuleForm.value.name,
        path: updateRuleForm.value.path,
        modelId: route.query.id,
        viewGroupIds: updateRuleForm.value.viewGroupIds,
        contriGroupIds: updateRuleForm.value.contriGroupIds,
        picPaths: updateRuleForm.value.picPaths,
        picDescs: updateRuleForm.value.picDescs,
        userIds: updateRuleForm.value.userIds,
        attachmentPaths: updateRuleForm.value.attachmentPaths,
        attachmentNames: updateRuleForm.value.attachmentNames,
        attachmentFilenames: updateRuleForm.value.attachmentFilenames,
        attachmentDescribes: updateRuleForm.value.attachmentDescribes,
        fileGroupIds: updateRuleForm.value.fileGroupIds,
        picOrders: updateRuleForm.value.picOrders,
        oldattachmentPaths: updateRuleForm.value.oldattachmentPaths,
        title: updateRuleForm.value.title,
        keywords: updateRuleForm.value.keywords,
        description: updateRuleForm.value.description,
        tplChannel: updateRuleForm.value.tplChannel,
        tplContent: updateRuleForm.value.tplContent,
        channelRule: updateRuleForm.value.channelRule,
        contentRule: updateRuleForm.value.contentRule,
        link: updateRuleForm.value.link,
        display: updateRuleForm.value.display === '1',
        finalstep: 0
      }
      createChildColumn(params).then((res) => {
        if (res.success) {
          ElMessage({
            type: 'success',
            message: res.message
          })
          router.push({ path: 'ColumnManagement' })
        }
      })
      console.log(params)
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 弹窗重置
const resetUpdateForm = (formEl) => {
  updateRuleForm.value = {
    channelId: '',
    parentId: '',
    root: '',
    name: '',
    path: '',
    priority: '',
    display: '',
    title: '',
    keywords: '',
    description: '',
    tplChannel: '',
    tplContent: '',
    channelStatic: '',
    contentStatic: '',
    finalStep: '',
    afterCheck: '',
    link: '',
    modelId: '',
    viewGroupIds: [],
    contriGroupIds: [],
    picPaths: [],
    picDescs: [],
    userIds: [],
    attachmentPaths: [],
    attachmentNames: [],
    attachmentFilenames: [],
    attachmentDescribes: [],
    fileGroupIds: [],
    picOrders: [],
    oldattachmentPaths: []
  }
  formEl.resetFields()
}

const handleInput = (val) => {
  console.log(123, val)
}

const onSelectChange = (value) => {
  console.log('选择改变，当前值：', value)
}

// 处理失去焦点事件
const handleBlur = (field) => {
  console.log(`${field} 输入框失去焦点`)
}

// 处理获取焦点事件
const handleFocus = (field) => {
  console.log(`${field} 输入框获取焦点`)
}
// 处理复选框值改变的事件
const onCheckboxChange = (values) => {
  console.log('选中的值改变了:', values)
}
getList()
</script>

<style lang="scss" scoped>
::v-deep {
  .el-form {
    .el-form-item {
      .el-form-item__label {
        font-weight: bold !important;
      }
    }
  }
}
</style>
